﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace CSE445_Assignment2_ChickenSales
{
    public delegate void orderDele(string order);
    // event orderDele sold;
    class cChickenFarm
    {

        public const int NUM = 100;
        public int cutCount = -1;
        static Random rng = new Random();
        public static event priceCutEvent priceCut; // Define event
        public static event chickenSoldEvent chcknSold;// Sold Chickens Event
        private static Int32 chickenPrice = 10;
        public Int32 getPrice() { return chickenPrice; }
        public static void changePrice(Int32 price)
        {
            if (price < chickenPrice)
            { // a price cut 
                if (priceCut != null)  // there is at least a subscriber
                    priceCut(price); // emit event to subscribers chcknSold
            }
            chickenPrice = price;
        }

        public void farmerFunc()
        {
            myApplication myne = new myApplication();
            for (Int32 i = 0; i < 10; i++)
            {
                Thread.Sleep(500);
                string x = "";
                x = myne.getOuttaLine();
                
                if (!(x.Equals("")))
                    processOrder(x);
                // Take the order from the queue of the orders;
                // Decide the price based on the orders
                Int32 p = PriceModel(); //rng.Next(5, 10); // Generate a random price
                // Console.WriteLine("New Price is {0}", p);
                cChickenFarm.changePrice(p);

            }
        }

        public void processOrder(string odor)
        {
            cOrderProcessing orderProc = new cOrderProcessing();
            cOrder thisOrder = new cOrder();
            cDecEnc decoder = new cDecEnc();
            thisOrder = decoder.Decode(odor);
            int x, y;
            long z;

            x = thisOrder.price;
            y = thisOrder.amount;
            z = thisOrder.cardNo;
            bool checkCredit = orderProc.verifyCredit(z);
            if (checkCredit)
            {

                Thread t = new Thread(delegate()
                    {
                        orderProc.charge(x, y);
                    });

                if (chcknSold != null)  // there is at least a subscriber
                    chcknSold(thisOrder.senderID, y); // emit event to subscribers chcknSold
            }
        }

        public int PriceModel()
        {
            int[] arrCost = { 10, 9, 5, 7, 6, 10, 9, 8, 5, 6 };
            cutCount++;
            return arrCost[cutCount];

        }
    }

}